package com.haixinga.kits;

import org.apache.commons.lang3.ArrayUtils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @Author terrfly
 * @Date 2020/12/23 19:11
 * @Description RSA加解密工具包
 **/
public class RSAEncryptUtils {


    // RSA最大加密明文大小
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     *
     * 定义私钥长度
     * 用于解密ras秘钥
     * 最大解密长度应等于密钥长度/8（1byte=8bit），所以当密钥位数为2048时，最大解密长度应为256. 【128 对应 1024 ； 256对应2048】
     *
     * Cipher提供加解密API，其中RSA非对称加密解密内容长度是有限制的，加密长度不超过117Byte，解密长度不超过128Byte，
     * 报错如下：javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes。
     *
     *  **/
    public enum SizeEnum {

        L1024(1024), L2048(2048);

        private int keyLength;
        public int getKeyLength() {
            return this.keyLength;
        }

        SizeEnum(int keyLength) {
            this.keyLength = keyLength;
        }

    }

    /**  rsa加密 (公钥加密)  **/
    public static String encrypt(String originText, String publicKey) throws Exception {

        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        // 加密时超过117字节就报错。为此采用分段加密的办法来加密
        byte[] data = originText.getBytes("UTF-8");
        byte[] enBytes = null;
        for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) {
            // 注意要使用2的倍数，否则会出现加密后的内容再解密时为乱码
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_ENCRYPT_BLOCK));
            enBytes = ArrayUtils.addAll(enBytes, doFinal);
        }

        return Base64.getEncoder().encodeToString(enBytes);
    }

    /**  rsa私钥解密  **/
    public static String decrypt(String encryStr, String privateKey, SizeEnum sizeEnum) throws Exception {


        int maxDecryptBlock = sizeEnum.getKeyLength() / 8; //最大解密长度

        byte[] data = Base64.getDecoder().decode(encryStr); //待解密报文

        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        // 解密时超过字节报错。为此采用分段解密的办法来解密
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length; i += maxDecryptBlock) {
            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + maxDecryptBlock));
            sb.append(new String(doFinal));
        }

        return sb.toString();
    }

}
